﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using hStatsC.Helper;
using hStatsC.Models;
using Panuon.UI.Silver;
using PropertyChanged;

namespace hStatsC.Views
{
    [AddINotifyPropertyChangedInterface]
    public partial class AppVersionsView : UserControl
    {
        public AppInfo App { get; set; }

        public ObservableCollection<AppVersion> Versions { get; set; }

        public AppVersionsView()
        {
            InitializeComponent();
            DataContext = this;
        }

        private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Versions = new(MainHelper.AllVersions(App.App));
        }

        private void Btn_Edit(object sender, RoutedEventArgs e)
        {
            MessageBoxX.Show("暂不开放编辑");
        }

        private void Btn_Delete(object sender, RoutedEventArgs e)
        {
            try
            {
                AppVersion v = (sender as Button).DataContext as AppVersion;
                if (MainHelper.DeleteVersion(v.App, v))
                {
                    MessageBoxX.Show("删除版本成功,正在为你刷新数据。", "成功");
                    RefreshVersions();
                }
                else
                {
                    MessageBoxX.Show("删除失败!");
                }

            }
            catch (Exception exception)
            {
                MessageBoxX.Show($"App版本删除异常\n{exception.Message}", "异常");

            }
            
        }

        private void Btn_AddVersion(object sender, RoutedEventArgs e)
        {
            try
            {
                var view = new AppVersionDetailView(true, App.App);
                if (view.ShowDialog() == true)
                {
                    //正确的App
                    var result = MainHelper.AddVersion(App.App, view.Version);
                    if (result)
                    {
                        MessageBoxX.Show("添加成功\n正在为你刷新版本信息");
                        RefreshVersions();
                    }
                    else
                    {
                        MessageBoxX.Show("添加失败:可能已经存在相同版本或者AccessToken异常\n尝试重启程序~");
                    }
                }
            }
            catch (Exception exception)
            {
                MessageBoxX.Show($"App版本添加异常\n{exception.Message}", "异常");
            }
        }

        private void RefreshVersions()
        {
            Versions = new(MainHelper.AllVersions(App.App));
        }
    }
}